/**
 * 校园二手交易平台 - Mock数据演示脚本
 * 用于快速测试和演示Mock数据功能
 */

import { MockDataUtils, MockDebugUtils } from './mockUtils';
import { Product, ProductCategory, ProductStatus } from '../types/product';

/**
 * Mock数据演示类
 */
export class MockDemo {
  private products: Product[] = [];
  
  /**
   * 初始化演示数据
   */
  async initialize(): Promise<void> {
    console.log('🚀 初始化Mock数据演示...');
    
    // 生成演示数据
    this.products = MockDataUtils.generateProducts(50);
    
    console.log('✅ Mock数据生成完成');
    console.log(`📊 总商品数: ${this.products.length}`);
  }
  
  /**
   * 演示数据统计
   */
  demoStatistics(): void {
    console.log('\n📈 数据统计演示');
    console.log('='.repeat(50));
    
    MockDebugUtils.logMockStats(this.products);
  }
  
  /**
   * 演示分类筛选
   */
  demoCategoryFiltering(): void {
    console.log('\n🔍 分类筛选演示');
    console.log('='.repeat(50));
    
    const categories = Object.values(ProductCategory);
    
    categories.forEach(category => {
      const categoryProducts = this.products.filter(p => p.category === category);
      console.log(`🏷️ ${category}: ${categoryProducts.length} 件商品`);
      
      if (categoryProducts.length > 0) {
        const sample = categoryProducts[0];
        console.log(`  示例: ${sample.title} - ¥${sample.price}`);
      }
    });
  }
  
  /**
   * 演示价格分布
   */
  demoPriceDistribution(): void {
    console.log('\n💰 价格分布演示');
    console.log('='.repeat(50));
    
    const priceRanges = [
      { min: 0, max: 50, label: '50元以下' },
      { min: 50, max: 100, label: '50-100元' },
      { min: 100, max: 200, label: '100-200元' },
      { min: 200, max: 500, label: '200-500元' },
      { min: 500, max: 1000, label: '500-1000元' },
      { min: 1000, max: Infinity, label: '1000元以上' }
    ];
    
    priceRanges.forEach(range => {
      const count = this.products.filter(p => p.price >= range.min && p.price < range.max).length;
      const percentage = ((count / this.products.length) * 100).toFixed(1);
      console.log(`${range.label}: ${count} 件 (${percentage}%)`);
    });
  }
  
  /**
   * 演示新旧程度分布
   */
  demoConditionDistribution(): void {
    console.log('\n🔄 新旧程度演示');
    console.log('='.repeat(50));
    
    const conditions = {
      new: '全新',
      like_new: '九成新',
      very_good: '八成新',
      good: '七成新',
      fair: '六成新',
      poor: '五成新及以下'
    };
    
    Object.entries(conditions).forEach(([key, label]) => {
      const count = this.products.filter(p => p.condition === key).length;
      const percentage = ((count / this.products.length) * 100).toFixed(1);
      console.log(`${label}: ${count} 件 (${percentage}%)`);
    });
  }
  
  /**
   * 演示学校分布
   */
  demoSchoolDistribution(): void {
    console.log('\n🏫 学校分布演示');
    console.log('='.repeat(50));
    
    const schools = new Set(this.products.map(p => p.location.school));
    
    schools.forEach(school => {
      const count = this.products.filter(p => p.location.school === school).length;
      const percentage = ((count / this.products.length) * 100).toFixed(1);
      console.log(`${school}: ${count} 件 (${percentage}%)`);
    });
  }
  
  /**
   * 演示商品样本
   */
  demoSampleProducts(): void {
    console.log('\n🎯 商品样本演示');
    console.log('='.repeat(50));
    
    // 按类别各取一个样本
    const categories = Object.values(ProductCategory);
    
    categories.forEach(category => {
      const sample = this.products.find(p => p.category === category);
      if (sample) {
        console.log(`\n📚 ${category.toUpperCase()}`);
        console.log(`   标题: ${sample.title}`);
        console.log(`   价格: ¥${sample.price} (原价: ¥${sample.originalPrice})`);
        console.log(`   新旧: ${sample.condition}`);
        console.log(`   学校: ${sample.location.school}`);
        console.log(`   状态: ${sample.status}`);
        console.log(`   发布者: ${sample.publisher.username}`);
      }
    });
  }
  
  /**
   * 演示搜索功能
   */
  demoSearchFunctionality(): void {
    console.log('\n🔎 搜索功能演示');
    console.log('='.repeat(50));
    
    const searchKeywords = ['笔记本', '教材', '运动', '二手', '校园'];
    
    searchKeywords.forEach(keyword => {
      const results = this.products.filter(p => 
        p.title.toLowerCase().includes(keyword.toLowerCase()) ||
        p.description.toLowerCase().includes(keyword.toLowerCase()) ||
        p.tags?.some(tag => tag.toLowerCase().includes(keyword.toLowerCase()))
      );
      
      console.log(`🔍 搜索 "${keyword}": 找到 ${results.length} 个结果`);
      
      if (results.length > 0) {
        console.log(`   示例: ${results[0].title} - ¥${results[0].price}`);
      }
    });
  }
  
  /**
   * 运行完整演示
   */
  async runFullDemo(): Promise<void> {
    console.log('🎪 开始Mock数据完整演示\n');
    
    await this.initialize();
    
    this.demoStatistics();
    this.demoCategoryFiltering();
    this.demoPriceDistribution();
    this.demoConditionDistribution();
    this.demoSchoolDistribution();
    this.demoSampleProducts();
    this.demoSearchFunctionality();
    
    console.log('\n🎉 Mock数据演示完成！');
    console.log('💡 提示: 这些数据可用于前端开发和测试');
  }
  
  /**
   * 生成测试报告
   */
  generateTestReport(): {
    summary: string;
    details: any;
    recommendations: string[];
  } {
    const stats = MockDataUtils.analyzeMockData(this.products);
    
    return {
      summary: `Mock数据测试报告 - 共 ${this.products.length} 件商品`,
      details: {
        totalProducts: this.products.length,
        categoryCoverage: Object.keys(stats.byCategory).length,
        priceRange: `¥${stats.priceStats.min} - ¥${stats.priceStats.max}`,
        averagePrice: `¥${stats.priceStats.avg}`,
        statusDistribution: stats.byStatus
      },
      recommendations: [
        '数据分布合理，适合开发测试',
        '价格区间覆盖全面，测试各种场景',
        '学校信息真实，符合校园特色',
        '建议增加更多商品描述细节'
      ]
    };
  }
}

/**
 * 快速演示函数
 */
export async function quickDemo(): Promise<void> {
  const demo = new MockDemo();
  await demo.runFullDemo();
}

/**
 * 命令行演示工具
 */
if (typeof window === 'undefined') {
  // Node.js 环境
  quickDemo().catch(console.error);
}

export default MockDemo;